TOOL.Category = '(Water Works)'
TOOL.Name = 'Devices'
TOOL.Command = nil
TOOL.ConfigName = ''

TOOL.ClientConVar['wtype'] = 'smallnozzle'

if ( CLIENT ) then
	language.Add( 'Tool_waterdev_name', 'Water Works Devices (PhonicUK)' )
	language.Add( 'Tool_waterdev_desc', 'Create Water Works Devices.' )
	language.Add( 'Tool_waterdev_0', 'Click to spawn a device. Right click to spawn without weld.' )
	language.Add( 'Undone_waterdev', 'Undone Water Works Device' )
end

function TOOL.BuildCPanel( panel )
	panel:AddControl( 'Header', { Text = '#Tool_waterdev_name', Description	= '#Tool_waterdev_desc' }  )

	local combobox = {Label = "#Water Works Device Type", MenuButton = 0, Options={}}
		combobox["Options"]["#Small Pump Nozzle"]	= { waterdev_wtype = "nozzle_small" }
		combobox["Options"]["#Large Pump Nozzle"]	= { waterdev_wtype = "nozzle_large" }
		combobox["Options"]["#Small Water Pump"]	= { waterdev_wtype = "pump_small" }
		combobox["Options"]["#Large Water Pump"]	= { waterdev_wtype = "pump_large" }
		combobox["Options"]["#Micro Water Boiler"]	= { waterdev_wtype = "boiler_tiny" }
		combobox["Options"]["#Small Water Boiler"]	= { waterdev_wtype = "boiler_small" }
		combobox["Options"]["#Large Water Boiler"]	= { waterdev_wtype = "boiler_large" }
		combobox["Options"]["#Moisture Water Scoop"]	= { waterdev_wtype = "moisture_scoop" }
	panel:AddControl("ComboBox", combobox) 
end

function TOOL:LeftClick( trace )
	local Ang = trace.HitNormal:Angle()
 	Ang.pitch = Ang.pitch + 90
	createdev( trace, true, self, self:GetClientInfo('wtype'), Ang )
	return true
end    

function TOOL:RightClick( trace )
	local Ang = trace.HitNormal:Angle() 
 	Ang.pitch = Ang.pitch + 90
	createdev( trace, false, self, self:GetClientInfo('wtype'), Ang )
	return true
end

function createdev(trace, weldit, self1, gentype, ang)
	if( SERVER ) then
		-- Get trace entity
		local ent0 = trace.Entity
	
		--Create generator
		local ent1 = ents.Create( gentype )
		ent1:SetAngles( ang ) 
		ent1:SetPos( trace.HitPos - trace.HitNormal * ent1:OBBMins().z)
		ent1:Spawn()
		ent1:Activate()
		ent1:SetVar('Owner',self1:GetOwner())
	
		-- Weld it only to props
		if (weldit == true) then
		local weld = constraint.Weld(ent0, ent1, trace.PhysicsBone, 0, 0)
		end 
	
		-- This seems not to work :S:S:S:S:S:S:S
		undo.Create("waterdev")  
			undo.AddEntity( ent1 ) 
			undo.AddEntity( weld )
			undo.SetPlayer( self1:GetOwner() ) 
		undo.Finish()
		return ent1
	end
end